<script setup name="MenuAuthIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import {
  listRole,
  delRole,
  updateRole,
  dataScope,
  getRole
} from "@/api/system/role";
import { roleMenuTreeselect } from "@/api/system/menu";
import { roleDeptTreeselect } from "@/api/system/dept";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  treeLoading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  form: {
    dataScope: ""
  },
  // 搜索
  search: {
    name: "",
    deptId: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  // 树权限数据
  treeDataList: [],
  //选中的数据
  checkedKeys: [],
  deptCheckedKeys: [],
  //是否是管理员
  isAdmin: false,
  // 角色信息
  role: {},
  // 部门权限
  deptList: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.roleName && (params.roleName = data.value.search.roleName);
  listRole(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list;
    pagination.value.total = res.data.total;
  });
}

const activeName = ref("menuAuth");
const handleClick = (tab, event) => {
  console.log(tab.props.name, event);
};
// 选项角色 获取菜单权限和数据权限
function selectRole(row, column, event) {
  data.value.treeLoading = true;
  if (row.roleKey != "admin") {
    data.value.isAdmin = true;
    data.value.role = row;
    roleMenuTreeselect(row.id).then((res) => {
      data.value.treeDataList = res.data.menus;
      data.value.checkedKeys = res.data.checkedKeys;
    });
    getRole(row.id).then((res) => {
      data.value.role = res.data;
    });
    if (data.value.role.dataScope == "2") {
      datascopeselect("2");
    }
  } else {
    data.value.isAdmin = false;
  }
  data.value.treeLoading = false;
}
const treeRef = ref();
// 给角色授权
function roleAuthMenu() {
  console.log(treeRef.value.getCheckedKeys(false));
  data.value.role.menuIds = treeRef.value.getCheckedKeys(false);
  updateRole(data.value.role).then((res) => {
    if (res.code == 200) {
      ElMessage.success({
        message: res.msg,
        center: true
      });
    } else {
      ElMessage.error({
        message: res.msg,
        center: true
      });
    }
  });
}
const dataScopeDeptRef = ref();
// 给角色数据权限
function submitDataScope() {
  if (data.value.role.dataScope == "2") {
    data.value.role.deptIds = dataScopeDeptRef.value.getCheckedKeys(false);
  }
  dataScope(data.value.role).then((res) => {
    if (res.code == 200) {
      ElMessage.success({
        message: res.msg,
        center: true
      });
    } else {
      ElMessage.error({
        message: res.msg,
        center: true
      });
    }
  });
}
// 下拉数据权限
function datascopeselect(value) {
  if (value == "2") {
    roleDeptTreeselect(data.value.role.id).then((res) => {
      data.value.deptList = res.data.depts;
      data.value.deptCheckedKeys = res.data.checkedKeys;
    });
  }
}

const defaultProps = {
  children: "children",
  label: "label"
};
const dataScopeOptions = [
  {
    value: "1",
    label: "全部数据权限"
  },
  {
    value: "2",
    label: "自定义数据权限"
  },
  {
    value: "3",
    label: "本部门数据权限"
  },
  {
    value: "4",
    label: "本部门及以下数据权限"
  },
  {
    value: "5",
    label: "仅本人数据权限"
  }
];
</script>

<template>
  <div>
    <el-row :gutter="0">
      <el-col :span="10">
        <page-main style="height: calc(100vh - 160px); margin: 10px">
          <search-bar>
            <el-form
              :model="data.search"
              size="default"
              label-width="auto"
              label-suffix=""
            >
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="角色名称">
                    <el-input
                      v-model="data.search.roleName"
                      placeholder="请输入角色名称"
                      clearable
                      @keydown.enter="currentChange()"
                      @clear="currentChange()"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="5">
                  <el-form-item>
                    <el-button type="primary" @click="currentChange()">
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ep:search" />
                        </el-icon>
                      </template>
                      查询
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </search-bar>

          <div style="height: calc(100vh - 340px); overflow-y: auto">
            <el-table
              ref="table"
              v-loading="data.loading"
              class="list-table"
              :data="data.dataList"
              border
              highlight-current-row
              row-key="id"
              @sort-change="sortChange"
              @selection-change="data.batch.selectionDataList = $event"
              @row-click="selectRole"
            >
              >
              <el-table-column
                type="index"
                align="center"
                label="序号"
                width="80"
              />
              <el-table-column prop="roleName" label="岗位名称">
              </el-table-column>
              <el-table-column prop="roleKey" label="岗位编码" align="center">
              </el-table-column>
              <el-table-column prop="status" label="状态" align="center">
                <template v-slot="scope">
                  <el-tag v-if="scope.row.status == '0'" effect="Light"
                    >正常</el-tag
                  >
                  <el-tag v-else effect="Light" type="warning">停用</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <el-pagination
            :current-page="pagination.page"
            :total="pagination.total"
            :page-size="pagination.size"
            :page-sizes="pagination.sizes"
            :layout="pagination.layout"
            :hide-on-single-page="false"
            class="pagination"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </page-main>
        <FormMode
          v-if="['dialog', 'drawer'].includes(data.formMode)"
          :id="data.formModeProps.id"
          v-model="data.formModeProps.visible"
          :mode="data.formMode"
          @success="getDataList"
        />
      </el-col>
      <el-col :span="14">
        <page-main style="height: calc(100vh - 160px); margin: 10px">
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            border-card
            v-if="data.isAdmin"
          >
            <el-tab-pane label="菜单权限" name="menuAuth">
              <div style="height: calc(100vh - 260px); overflow-y: auto">
                <el-card>
                  <template #header>
                    <el-row>
                      <el-col :span="12"> 菜单选择 </el-col>
                      <el-col style="text-align: right" :span="12">
                        <el-button type="primary" @click="roleAuthMenu"
                          >保存</el-button
                        >
                      </el-col>
                    </el-row>
                  </template>
                  <el-tree
                    ref="treeRef"
                    :data="data.treeDataList"
                    show-checkbox
                    :default-checked-keys="data.checkedKeys"
                    node-key="id"
                    highlight-current
                    :props="defaultProps"
                    :default-expanded-keys="data.checkedKeys"
                  />
                </el-card>
              </div>
              <!--  -->
            </el-tab-pane>
            <el-tab-pane label="数据权限" name="dataAuth">
              <el-card>
                <template #header>
                  <el-row>
                    <el-col :span="12"
                      >权限范围：
                      <el-select
                        placeholder="请选择"
                        v-model="data.role.dataScope"
                        @change="datascopeselect"
                      >
                        <el-option
                          v-for="(d, index) in dataScopeOptions"
                          :key="index"
                          :value="d.value"
                          :label="d.label"
                        /> </el-select
                    ></el-col>

                    <el-col style="text-align: right" :span="12">
                      <el-button type="primary" @click="submitDataScope">
                        保存
                      </el-button>
                    </el-col>
                  </el-row>
                </template>
                <el-tree
                  ref="dataScopeDeptRef"
                  :data="data.deptList"
                  show-checkbox
                  :default-checked-keys="data.deptCheckedKeys"
                  node-key="id"
                  highlight-current
                  :props="defaultProps"
                  :default-expanded-keys="data.deptCheckedKeys"
                  v-if="data.role.dataScope == '2'"
                />
              </el-card>
            </el-tab-pane>
          </el-tabs>
          <div
            v-else
            style="
              height: 20vh;
              font-size: 16px;
              color: darkgray;
              line-height: 20vh;
              text-align: center;
            "
          >
            超级管理员不受权限控制,其余角色根据需求设置菜单,小页以及数据权限
          </div>
        </page-main>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
